import {useMutation, useQuery, useQueryClient} from "@tanstack/vue-query"
import userApi from "@/api/sys/user"

export function useSysUserPage(paramsRef) {
    return useQuery({
        queryKey: ["sysUserPage", paramsRef.value],  // 缓存 key
        queryFn: () => userApi.page(paramsRef.value),
        // 翻页时保持上一次数据
        keepPreviousData: true,
    })
}

export function useSysUserInfo(idRef) {
    return useQuery({
        queryKey: computed(() => ["sysUserInfo", idRef.value]),
        queryFn: () => userApi.info(idRef.value),
        enabled: computed(() => !!idRef.value),
    })
}

export const useSysUserMutations = () => {
    const queryClient = useQueryClient()

    // 统一的缓存失效方法
    const invalidateUserCaches = async (id) => {
        // 刷新分页列表
        await queryClient.invalidateQueries({queryKey: ['sysUserPage'], exact: false});
        // 刷新单条用户详情（如果提供了 id）
        if (id) {
            await queryClient.invalidateQueries({queryKey: ['sysUserInfo', id]});
        }
    }

    const create = useMutation({
        mutationFn: (data) => userApi.create(data),
        onSuccess: () => invalidateUserCaches()
    })

    const update = useMutation({
        mutationFn: (data) => userApi.update(data),
        onSuccess: (_, data) => invalidateUserCaches(data.id),
    })

    const remove = useMutation({
        mutationFn: (id) => userApi.delete(id),
        onSuccess: (_, id) => invalidateUserCaches(id),
    })

    const removeBatch = useMutation({
        mutationFn: (ids) => userApi.deleteBatch(ids),
        onSuccess: () => invalidateUserCaches(),
    })

    const resetPassword = useMutation({
        mutationFn: (id) => userApi.resetPassword(id),
    })

    const lock = useMutation({
        mutationFn: (id) => userApi.lock(id),
        onSuccess: () => invalidateUserCaches(),
    })

    const unlock = useMutation({
        mutationFn: (id) => userApi.unlock(id),
        onSuccess: () => invalidateUserCaches(),
    })

    return {create, update, remove, removeBatch, resetPassword, lock, unlock}
}
